﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;
using SP.Service.DTO;
using SP.Domain.Model;
using SP.Service;
using Swashbuckle.AspNetCore.Annotations;
using SP.User.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using SP.EFcore.Helpers.JWT;
using SP.Domain.DTO;

namespace SP.User.WebApi.Controllers
{
    /// <summary>
    /// 用户模块
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize] //授权特性 ：该控制器的所有方法，必须登陆之后才能调用，否则返回401
    public class UserController : ControllerBase
    {
        private readonly IUserService _user;
        private readonly JwtHelp _jwtHelp;
        public UserController(IUserService user, JwtHelp jwtHelp)
        {
            _user = user;
            _jwtHelp = jwtHelp;
        }
        static CSRedis.CSRedisClient redis = new CSRedis.CSRedisClient("127.0.0.1:6379");
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="UserName"></param>
        /// <returns></returns>
        [HttpGet("USerList")]

        public IActionResult USerList(int pageIndex, int pageSize, string UserName)
        {
            return Ok(_user.UserList(pageIndex, pageSize, UserName));
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        //[Route("{Name}/{PassWord}")] //Route路由传参就是用
        [AllowAnonymous]//允许匿名访问
        [SwaggerOperation(Summary = "用户登录")]
        public IActionResult Login( LoginDTO model)
        {//抛异常
         //int i = 0;
         //int y = 10 / i;
         //第一步做模型验证
            if (!ModelState.IsValid)
            {
                //如果输入的参数无效，则直接返回
                return BadRequest();    //返回一个404状态码
            }
            //获取用户
            var result = _user.Login(model);
            if (result == null)
            {
                return Ok(new { code = -1, msg = "用户登录失败", date = result });
            }
            else
            {
                //荷载信息
                List<Claim> claims=new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,result.UserName),
                    new Claim(ClaimTypes.NameIdentifier, result.Id.ToString()),
                };
                //把用户的信息暂存到redis里边
                string refreshToken = Guid.NewGuid().ToString();//生成刷新令牌 
                redis.Set(refreshToken, result, 3 * 24 * 3600);//保存到redis数据库

                return Ok(new { code = 0, msg = "用户登录成功", date = result,RefreshToken=refreshToken,Token=_jwtHelp.CreateToken(claims) });
            }
        }
        [HttpGet("GetNewToken")]
        [AllowAnonymous]//允许匿名
        public IActionResult GetNewToken(string refreshToken)
        {
            var user = redis.Get<LoginDTO>(refreshToken);
            if (user != null)
            {
                //荷载信息
                List<Claim> claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,user.UserName),
                    //new Claim(ClaimTypes.NameIdentifier, model.Id.ToString()),
                };
                //把用户的信息暂存到redis里边
                string refreshTokenNew = Guid.NewGuid().ToString();//生成刷新令牌 
                redis.Del(refreshToken);
                redis.Set(refreshTokenNew, user, 3 * 24 * 3600);//保存到redis数据库
                return Ok(new { code = 0, msg = "用户登录成功", RefreshToken = refreshTokenNew, Token = _jwtHelp.CreateToken(claims) });
            }
            else
            {
                //令牌失效
                return Ok(new { code = 0, msg = "令牌失效", RefreshToken = "", Token = "" });
            }
        }
        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddUser")]
        [SwaggerOperation(Summary = "用户添加")]
        public IActionResult AddUser(UserTable model)
        {
            //模型验证
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var result = _user.AddUser(model);
            if (result>0)
            {
                return Ok(new {code=200,msg="添加成功",data=result });
            }
           else
            {
                return Ok(new { code = 400, msg = "异常错误", data = result });
            }
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("UpdUser")]
        [SwaggerOperation(Summary = "用户修改")]
        public IActionResult UpdUser(UserTable model)
        {
            return Ok(_user.UpdateUser(model));
        }
        /// <summary>
        /// 用户显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="UserName"></param>
        /// <returns></returns>
        [HttpGet("UsersList")]
       // [Authorize]//授权特性，表示：下面的控制器中所有方法，都必须登陆之后才能访问
        [SwaggerOperation(Summary = "用户列表")]
        public IActionResult UsersList(int pageIndex, int pageSize, string? UserName)
        {
            return Ok(_user.UserList(pageIndex, pageSize, UserName));
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("DeleteUser")]
        [SwaggerOperation(Summary = "用户删除")]
        public IActionResult DeleteUser(UserTable model)
        {
            return Ok(_user.DeleteUser(model));
        }
        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("BatchUser")]
        public IActionResult BatchUser(string id)
        {
            //判断id不能为空
            if (id==null)
            {
                 return BadRequest();
            }
            var result = _user.BatckUser(id);
            if (result==null)
            {
                return Ok(new {code=400,msg="异常错误",data=result });
            }
            else
            {
                return Ok(new { code = 200, msg = "删除成功", data = result });
            }
        }
        /// <summary>
        /// 用户反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("FindUser")]
        public IActionResult FindUser(int id)
        {
            //判断id不能为空
            if (id==null)
            {
                return BadRequest();
            }
            var result=_user.FindUser(id);
            if (result==null)
            {
                return Ok(new {code=400,msg="异常错误",data=result });
            }
            else
            {
                return Ok(new { code = 200, msg = "获取成功", data = result });
            }
        }
    }
}
